package com.filter;

import com.dao.RecordDao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class RecordFilter implements Filter {
    /**
     * 处理用户访问记录的过滤器
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 所有跟请求相关的数据，都被 tomcat 封装到 request 对象里
        HttpServletRequest req = (HttpServletRequest) request;
        String url = req.getRequestURI();
        String ip = req.getRemoteAddr();
        String userAgent = req.getHeader("user-agent");

        // 便于开发时查看结果
        System.out.println("url: " + url + " up: " + ip + " userAgent: " + userAgent);

        // 将相关的数据插入到数据库
        RecordDao recordDao = new RecordDao();
        try {
            recordDao.insert(url, ip, userAgent);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 继续
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
